<!---
Title: 		Create Experiment
Filename: 	ce.cfm
Description:	First page in the experiment creation process. An HTML form with postback. Allows users to define their experiment.
--->
<cfif Not IsDefined("session.id")>
	<cfset session.message="Not logged in!">
	<cflocation url="/ecada/" addToken="no"><!--- site root --->
</cfif>

<cfinclude template="/ecada/header.cfm">

<!--- Form postback. Everything contained within this CFIF will be executed when the user presses 'Next'. --->
<cfif IsDefined("form.next")>
	<!---split date and time up--->
	<cfset startdate = ListToArray(#sDate#, "-")>
	<cfset enddate = ListToArray(#eDate#, "-")/>
	<cfset starttime = ListToArray(#sTime#, ":")>
	<cfset endtime = ListToArray(#eTime#, ":")/>
	
	<!--- NOTE: ColdFusion arrays begin indexing at 1. --->

	<cfset startDate = CreateDateTime(startdate[3], startdate[2], startdate[1],
    starttime[1],starttime[2],0)>
	<cfset endDate = CreateDateTime(enddate[3], enddate[2], enddate[1],
    endtime[1],endtime[2],0)>
	<cfif IsDefined("form.ethicsFile") AND IsDefined("form.debriefFile")>
			<!---Ethics--->
			<!--- create a unique identifier--->
		<cfset folderUID = CreateUUID()>
		<!--- create folder--->
		<cfdirectory action = "create" directory = "#ExpandPath('/ecada/files/' & folderUID)#" mode = 777 >
	<!---upload file although it's more of a move file---->
		<cffile action="UPLOAD" 
			destination="#ExpandPath('/ecada/files/' & folderUID)#" 
			nameconflict="MAKEUNIQUE" 
			filefield="ethicsFile"
			result="FileDetails">
			<!---if it's not a pdf, convert it--->
		<cfif FileDetails.ServerFileExt neq "pdf">
			<!---set path--->
			<cfset RunningLogPath ="#ExpandPath('/ecada/files/' & folderUID)#">
			<!---read file into a variable---->
			<cffile action = "read" file ="#ExpandPath('/ecada/files/' & folderUID)#/#FileDetails.ServerFile#" variable = "eth">
			<!---create pdf--->
			<cfdocument format="pdf"
					 filename="#ExpandPath('/ecada/files/' & folderUID)#/ethics.pdf"
					 overwrite="true"
					 backgroundVisible="no"
					 pageType="custom"
		          pageWidth="7.8125"
					 pageHeight="5.2083">
					 <!---gotta have a document body--->
				<cfoutput>

							<table><tr><td><p>#eth#</p><td></tr></table>

				</cfoutput>	
			</cfdocument>
			<!--- insert that new pdf file into the filestore--->
			<cfquery datasource="exp" result="filestore">
				INSERT INTO filestore (filename, filepath, fileext, mimetype)
				VALUES ('ethics.pdf', '#folderUID#', 'pdf', 'application/pdf')
			</cfquery>
		<cfelse>
			<!--- it's a pdf.---->
			<cfquery datasource="exp" result="filestore">
				INSERT INTO filestore (filename, filepath, fileext, mimetype)
				VALUES ('#FileDetails.ServerFile#', '#folderUID#', '#FileDetails.ServerFileExt#', 'application/pdf')
			</cfquery>
		</cfif>
		<!---set EID(ethicsID) to the key we just created in the last query--->
		<cfset EID = filestore.generated_key><!---ethics File ID--->
			
		<!---the next big bit is literally just the baove over and over in a big if
			if(both have files)
			{
				process ethics
				process debrief
			}
			else
			{
				if(ethics)
				{
					process ethics
				}
				else if(debrief)
				{
					process debrief
				}
				else
				{
					set both EID AND DID to 1 and 2 respectivly
				}
			}
			
			--->
			
		<!---Debrief--->
		<cfset folderUID = CreateUUID()>
	
		<cfdirectory action = "create" directory = "#ExpandPath('/ecada/files/' & folderUID)#" mode = 777 >
	
		<cffile action="UPLOAD" 
			destination="#ExpandPath('/ecada/files/' & folderUID)#" 
			nameconflict="MAKEUNIQUE" 
			filefield="debriefFile"
			result="FileDetails">
			
		<cfif FileDetails.ServerFileExt neq "pdf">
		
			<cfset RunningLogPath = "#ExpandPath('/ecada/files/' & folderUID)#">

			<cffile action = "read" file ="#ExpandPath('/ecada/files/' & folderUID)#/#FileDetails.ServerFile#" variable = "eth">
		
			<cfdocument format="pdf"
					 filename="#ExpandPath('/ecada/files/' & folderUID)#/debrief.pdf"
					 overwrite="true"
					 backgroundVisible="no"
					 pageType="custom"
		          pageWidth="7.8125"
					 pageHeight="5.2083">

							<cfoutput>
							<table><tr><td><p>#eth#</p><td></tr></table>
				</cfoutput>
		
			</cfdocument>
		
			<cfquery datasource="exp" result="filestore">
				INSERT INTO filestore (filename, filepath, fileext, mimetype)
				VALUES ('debrief.pdf', '#folderUID#', 'pdf', 'application/pdf')
			</cfquery>
		<cfelse>
			<cfquery datasource="exp" result="filestore">
				INSERT INTO filestore (filename, filepath, fileext, mimetype)
				VALUES ('#FileDetails.ServerFile#', '#folderUID#', '#FileDetails.ServerFileExt#', '')
			</cfquery>
		</cfif>
		
		<cfset DID = filestore.generated_key><!---debrief File ID--->
	<cfelse>
		<cfif IsDefined("form.ethicsFile")>
				<cfset folderUID = CreateUUID()>
	
				<cfdirectory action = "create" directory = "#ExpandPath('/ecada/files/' & folderUID)#" mode = 777 >
	
				<cffile action="UPLOAD" 
					destination="#ExpandPath('/ecada/files/' & folderUID)#" 
					nameconflict="MAKEUNIQUE" 
					filefield="ethicsFile"
					result="FileDetails">
			
				<cfif FileDetails.ServerFileExt neq "pdf">
					<cfset RunningLogPath = "#ExpandPath('/ecada/files/' & folderUID)#">

					<cffile action = "read" file ="#ExpandPath('/ecada/files/' & folderUID)#/#FileDetails.ServerFile#" variable = "eth">
		
					<cfdocument format="pdf"
							 filename="#ExpandPath('/ecada/files/' & folderUID)#/ethics.pdf"
							 overwrite="true"
							 backgroundVisible="no"
							 pageType="custom"
						    pageWidth="7.8125"
							 pageHeight="5.2083">

									<cfoutput>
							<table><tr><td><p>#eth#</p><td></tr></table>
				</cfoutput>

					</cfdocument>
		
					<cfquery datasource="exp" result="filestore">
						INSERT INTO filestore (filename, filepath, fileext, mimetype)
						VALUES ('ethics.pdf', '#folderUID#', 'pdf', 'application/pdf')
					</cfquery>
				<cfelse>
					<cfquery datasource="exp" result="filestore">
						INSERT INTO filestore (filename, filepath, fileext, mimetype)
						VALUES ('#FileDetails.ServerFile#', '#folderUID#', '#FileDetails.ServerFileExt#', '')
					</cfquery>
				</cfif>
			
				<cfset EID = filestore.generated_key><!---ethics File ID--->
				<cfset DID = 2><!---debrief File ID--->
			
			<cfelseif IsDefined("form.debriefFile")>
				<cfset folderUID = CreateUUID()>
	
				<cfdirectory action = "create" directory = "#ExpandPath('/ecada/files/' & folderUID)#" mode = 777 >
	
				<cffile action="UPLOAD" 
					destination="#ExpandPath('/ecada/files/' & folderUID)#" 
					nameconflict="MAKEUNIQUE" 
					filefield="debriefFile"
					result="FileDetails">
				<cfif FileDetails.ServerFileExt neq "pdf">
		
					<cfset RunningLogPath = "#ExpandPath('/ecada/files/' & folderUID)#">

					<cffile action = "read" file ="#ExpandPath('/ecada/files/' & folderUID)#/#FileDetails.ServerFile#" variable = "eth">
		
					<cfdocument format="pdf"
							 filename="#ExpandPath('/ecada/files/' & folderUID)#/debrief.pdf"
							 overwrite="true"
							 backgroundVisible="no"
							 pageType="custom"
						    pageWidth="7.8125"
							 pageHeight="5.2083">
	
							<cfoutput>
							<table><tr><td><p>#eth#</p><td></tr></table>
				</cfoutput>
							
					</cfdocument>
		
					<cfquery datasource="exp" result="filestore">
						INSERT INTO filestore (filename, filepath, fileext, mimetype)
						VALUES ('debrief.pdf', '#folderUID#', 'pdf', 'application/pdf')
					</cfquery>
				<cfelse>
					<cfquery datasource="exp" result="filestore">
						INSERT INTO filestore (filename, filepath, fileext, mimetype)
						VALUES ('#FileDetails.ServerFile#', '#folderUID#', '#FileDetails.ServerFileExt#', '')
					</cfquery>
				</cfif>
		
				<cfset EID = 1><!---ethics File ID--->
				<cfset DID = filestore.generated_key><!---debrief File ID--->
			<cfelse>
				<cfset EID = 1><!---ethics File ID--->
				<cfset DID = 2><!---debrief File ID--->
			</cfif>
	</cfif>
	<!---This next query inserts creates the database entry for this experiment--->
	<cftransaction>
		<!--- Create experiment in the database. --->
		<cfquery datasource="exp" result="res">	
			INSERT INTO exper(OwnerID, Title, Description, MaxPart,
				startDate, endDate, StatusID, GroupID, EthicsID, DebriefID )
			VALUES
				( 
					#session.id#, <cfqueryparam value="#Expname#" cfsqltype="CF_SQL_VARCHAR">, <cfqueryparam value="#desc#" cfsqltype="CF_SQL_VARCHAR">, <cfqueryparam value="#maPar#" cfsqltype="CF_SQL_Integer">,
					#startDate#, #endDate#, (	
						SELECT st.id
						FROM expstatus st
						WHERE st.Status = 'incomplete'
					),
					#Group_SEL#,
					#EID#,
					#DID#
				) 
		</cfquery>	
	</cftransaction>

	<!--- avoid url params that are more easily modifiable session variable is  much much harder to hack---->

	<cfset currID = res.GENERATED_KEY>	
	<cfset experiment = StructNew()>
	<cfset experiment.id = res.GENERATED_KEY>
	<cfset session.experiment = experiment>

	<cflocation url="./../Step-2" addToken="no">
<!--- Everything contained in this CFELSE tag will be displayed when the user first sees the page. --->
<cfelse>

	
	<cfif IsDefined("session.experiment.id")>
		<cfquery datasource="exp" name="experi">
			SELECT *
			FROM experiment
			WHERE id = #session.experiment.id#
		</cfquery>
		
	</cfif>

	<cfoutput>
		<!--- This function for the datepicker was taken from the Jquery site: http://jqueryui.com/demos/datepicker/ --->
		<script type="text/javascript">
			/* This function is for the date/time scripts*/
			$(function() {
				var dates = $( "##from, ##to" ).datepicker({
					defaultDate: "-0d",//today
					minDate:'-0d',//today
					dateFormat: 'dd-mm-yy',/*jquery uses yy to represent a 4 digit year*/
					changeMonth: true,
					numberOfMonths: 1,/*modified from the example to only show one date box.*/
					onSelect: function( selectedDate ) {
						var option = this.id == "from" ? "minDate" : "maxDate",
							instance = $( this ).data( "datepicker" );
							date = $.datepicker.parseDate(
								instance.settings.dateFormat ||
								$.datepicker._defaults.dateFormat,
								selectedDate, instance.settings );
						dates.not( this ).datepicker( "option", option, date );
					},
				});
	
			});	
							
			$(document).ready(function() {
			
				//time picker from http://fgelinas.com/code/timepicker/
				$( "##from-time, ##to-time" ).timepicker();
				
				//jQuery spinner - unoffical release -- not fully suported.
				
				$('##maPar').spinner({ min: 1 , max: 100000000000, step: 10});//sets the max number of participants to 100 billion, should be plenty :)
				$('##maPar').css("margin-right", "0");
				$('##maPar').css("width", "auto");
				
				//this function is defined in progressbar.cfm and is included in the header
				setProgressText("Experiment Creator");
				setProgress(1);

			/*custom date validation, can't use the built in one as it can only check for American date standard. We must define a new validator for dates in the format dd-mm-yyyy and that is done with regular expressions*/
			$.validator.addMethod("pDate",
				function(value, element)

				{
					/*Regular Expression matches dd-mm-yyyy*/
					re = /^[0-3]?[0-9]-[01]?[0-9]-[12][90][0-9][0-9]$/;
					return value.match(re);
				},
				"<span style='color: red'>* Invalid</span>");
			$.validator.addMethod("Time",
				function(value, element)

				{
					/*Regular Expression matches dd-mm-yyyy*/
					re = /^([0-1][0-9]|2[0-3]):([0-5][0-9])$/;
					return value.match(re);
				},
				"<span style='color: red'>* Invalid</span>");

			/*this function is for form validation using jQuery. */
			$("##form1").validate({
				rules: {
						Expname: { required: true, maxlength: 40 },
						desc: { required: true, maxlength: 512},
						sDate: { required: true, pDate: true},
						eDate: { required: true, pDate: true},
						sTime: { required: true, Time: true},
						eTime: { required: true, Time: true}	
										
					}
				});
			}); 
		</script>
			<!--- Create experiment form. --->
			<!--- Just a basic form, submitted just does the optional file uploads--->
		<form style="color: black;" enctype="multipart/form-data" method = "post" id="form1" onsubmit="return Submitted();" action = "./">
			<fieldset>
				<legend>
					<b>Experiment details</b>
				</legend>
				
				<table>
					<tr>
						<td>Experiment Name	     </td>
						<td><input type = "text" size = "40" name = "Expname"></input></td>
					</tr>
					<tr>
						<td>Description          </td>
						<td><textarea cols="40" rows="5" name="desc"></textarea></td>
					</tr>
					<tr>
						<td>Group         </td>
						<td>
							<select name="Group_SEL" id="Group_SEL">
								<option value="-1" selected="selected">None</option>
								<!---get all the groups this user belongs too and dump them into a select box--->
								<cfquery datasource="exp" name="myGroups">
									SELECT g.name, g.id
									FROM groupusers ug, groups g
									WHERE ug.GroupID = g.id
									AND ug.UserID = #session.id#
								</cfquery>
								<cfloop query="myGroups">
									<option value="#id#">#HTMLEditFormat(name)#</option>
								</cfloop>
							</select>
						</td>
					</tr>
					<tr>
						<td>Start Date           </td>
						<td><input type ="text" id="from" value="#NumberFormat(day(Now()), '00')#-#NumberFormat(month(Now()), '00')#-#year(Now())#" name="sDate"></input>(dd-mm-yyyy hh:mm)</td>
					</tr>
					<tr>
						<td>Start Time           </td>
						<td><input type ="text" value="#NumberFormat(hour(now()), '00')#:#NumberFormat(minute(now()), '00')#" id="from-time" name="sTime"></input>(hh:mm)</td>
					</tr>
					<tr>
						<td>End Date          </td>
						<td><input type ="text" id="to" value="#NumberFormat(day(Now()+7), '00')#-#NumberFormat(month(Now()+7), '00')#-#year(Now()+7) #" name="eDate"></input>(dd-mm-yyyy hh:mm)</td>
					</tr>
					<tr>
						<td>End Time          </td>
						<td><input type ="text" value="00:00" id="to-time" name="eTime"></input>(hh:mm)</td>
					</tr>
					<tr>
						<td>Maximum Participants </td>
						<td><input type = "text" value="1" name="maPar" id="maPar" style="float: left; margin-right: 0 !important;"></input></td>
					</tr>
					</table>
				</fieldset>						
				<fieldset>
					<legend><b>Ethics &amp; Debrief</b></legend>
					<p>
						This can be in one of two formats: 
					</p> 
					<ol>
						<li>TXT file</li>
						<li>PDF file</li>
					</ol>
					<p>
						The txt file will be converted to a pdf. This conversion will convert it to a page size of roughly B5. If you upload a PDF it will be scaled down to B5 size. This scaling down to B5 size is to ensure that it fits on all participant monitor size's. It is highly recommened to just upload a PDF file.
					</p>
					Ethics&nbsp;&nbsp;<input type = "file" name="ethicsFile" id="ethicsFile"></input><br />
					Debrief&nbsp;<input type = "file" name="debriefFile" id="debriefFile"></input><br />
				</fieldset>
				<div style="float: right; margin: 10px; margin-top: 20px;">
					<button class="ui-state-default ui-corner-all" style="float: right; width: 75px; height: 50px;" name="next" title="Next" type="submit" value="Next">
						<div style="display: inline-block; margin: 3px;line-height: 16px;"><b>Next</b></div>
					</button>
				</div>
		</form>
		
		<script type="text/javascript">
			function Submitted()
			{
				<!---
				//The next two if's get around Coldfusions seemingly inability to handle optional file uploads.
				//Basically if you haven't uploaded a file then remove them from the form before submitting :)
				--->
				if($("##ethicsFile").exists() && $("##ethicsFile").val().length > 0)
				{
					//alert("ethics exists with a length of: " + $("##ethicsFile").val().length);
					//'sal good!
				}
				else
				{
					$("##ethicsFile").remove();
				}
				
				if($("##debriefFile").exists() && $("##debriefFile").val().length > 0)
				{
					//alert("ethics exists with a length of: " + $("##ethicsFile").val().length);
					//'sal good!
				}
				else
				{
					$("##debriefFile").remove();
				}
				
				
				return true;
			}
		</script>
		
	</cfoutput>
</cfif>
<cfinclude template="/ecada/footer.cfm">
